<?php


namespace app\apiadmin\model\choujiang;

use app\common\utils\Res;
use DateTime;
use MongoDB\BSON\UTCDateTime;
use think\Exception;
use think\facade\Db;
use think\Model;

class ChouJiangModel extends Model
{

    protected $name="siyu_prize";
    
    public static function list($brid)
    {
        $list =  self::where('brid',$brid)->order('create_time desc')->select();
        foreach ($list as $k =>$v){
            if ($v['lott_state'] == 0){
                $list[$k]['lott_state'] = '未开奖';
            }elseif ($v['lott_state'] == 1){
                $list[$k]['lott_state'] = '已开奖';
            }
        }
        foreach ($list as $vs){
            PrizeUserModel::where('prid',$vs['id'])->field('user_id')->find();
        }
        foreach ($list as $k=>$vs){
           $user_count = Db::table('xh_siyu_prize_user')->where('prid',$vs['id'])->count('user_id');
           $shuziren_count = Db::table('xh_siyu_prize_shuziren_user')->where('prid',$vs['id'])->count('user_id');
            $list[$k]['ratat_count'] = $user_count + $shuziren_count;
        }

        return $list;
    }
    public static function total($brid)
    {
        return self::where('brid',$brid)->count();
    }
    
    public static function getadd($param)
    {
        try {
            $data['brid'] = $param['liveId'];
            $data['title'] = $param['title'];
            $data['im_url'] = $param['im_url'];
            $data['number'] = $param['number'];
            $data['countdown'] = $param['countdown'];
            $data['pose_state'] = $param['pose_state'];
            $data['publish'] = $param['publish'];
            $alluser['user_id'] = isset($param['alluser'])?$param['alluser']:[];
            $allRobot['user_id'] = isset($param['alluser1'])?$param['alluser1']:[];
            $data['create_time'] = date('Y-m-d H:i:s',time());
            //  $pose['user_id'] = array_merge($alluser['user_id'],$allRobot['user_id']);
            if($data['pose_state']==1){
                $userCount = count($param['alluser']);
                $robootCount = count($param['alluser1']);
                $allCount  = $userCount + $robootCount;
                if ($allCount > 0){
                    if($allCount!=$data['number']){
                        return Res::error('预选人员不能小于或者大于抽奖数量');
                    }
                }else{
                    return Res::error('打开预设中奖未选择在线用户和机器人');
                }
            }
             
            $generateListModel = new ChouJiangModel();
            $re_data = $generateListModel->save($data);
            if($allRobot['user_id']){
                $prizeShuZiRenUserModel = new PrizeShuZiRenUserModel();
                foreach ($allRobot['user_id'] as $v){
                    $prizeShuZiRenUserModel->create(['prid'=>$generateListModel->id,'user_id'=>$v,'create_time' => date('Y-m-d H:i:s',time())]);
                }
            }
            if($alluser['user_id']){
                $prizeUserModel = new PrizeUserModel();
                foreach ($alluser['user_id'] as $value){
                    $prizeUserModel->create(['prid'=>$generateListModel->id,'user_id'=>$value,'create_time' => date('Y-m-d H:i:s',time())]);

                }
            }
            
//        foreach ($pose['user_id'] as $value) {
//            $prizeUserModel->create(['prid'=>$generateListModel->id,'user_id'=>$value,'create_time' => date('Y-m-d H:i:s',time())]);
//
//        }
            if($re_data){
                return Res::ok('添加成功');
            }else{
                return Res::error('添加失败');
            }
        }catch (\Exception $e){
            // 这是进行异常捕获
            return json($e->getMessage());
        }
        
    }
    public static function editPrize($param)
    {
        try {
            $data = [];
            $data['title'] = $param['title'];
            $data['im_url'] = $param['im_url'];
            $data['number'] = $param['number'];
            $data['countdown'] = $param['countdown'];
            $data['pose_state'] = $param['pose_state'];
            $data['publish'] = $param['publish'];
            $data['update_time'] = $param['update_time'];

            $alluser['user_id'] = isset($param['alluser'])?$param['alluser']:[];
            $allRobot['user_id'] = isset($param['alluser1'])?$param['alluser1']:[];
            if($data['pose_state']==1){
                $userCount = count($param['alluser']);
                $robootCount = count($param['alluser1']);
                $allCount  = $userCount + $robootCount;
                if ($allCount > 0){
                    if($allCount!=$data['number']){
                        return Res::error('预选人员不能小于或者大于抽奖数量');
                    }
                }else{
                    return Res::error('打开预设中奖未选择在线用户和机器人');
                }
            }else{
                $where=[
                    ['prid','=',$param['id']]
                ];
                PrizeShuZiRenUserModel::where($where)->delete();

                $where=[
                    ['prid','=',$param['id']]
                ];
                PrizeUserModel::where($where)->delete();
            }
            if ($allRobot['user_id']){
                $where=[
                    ['prid','=',$param['id']],
                    ['user_id','not in',$allRobot['user_id']]
                ];
                PrizeShuZiRenUserModel::where($where)->delete();
                foreach ($allRobot['user_id'] as $v){
                    $robot = PrizeShuZiRenUserModel::where('prid',$param['id'])->where('user_id',$v)->find();
                    if($robot){
                        //更新
                        PrizeShuZiRenUserModel::where('prid',$param['id'])->where('user_id',$v)->update(['update_time' => date('Y-m-d H:i:s',time())]);
                    }else{
                        //添加
                        PrizeShuZiRenUserModel::create(['prid'=>$param['id'],'user_id'=>$v,'create_time' => date('Y-m-d H:i:s',time())]);
                    }
                }
            }else{
                $where=[
                    ['prid','=',$param['id']]
                ];
                PrizeShuZiRenUserModel::where($where)->delete();
            }
            if($alluser['user_id']){
                $where=[
                    ['prid','=',$param['id']],
                    ['user_id','not in',$alluser['user_id']]
                ];
                PrizeUserModel::where($where)->delete();
                foreach ($alluser['user_id'] as $value){
                    $users = PrizeUserModel::where('prid',$param['id'])->where('user_id',$value)->find();
                    if ($users){
                        PrizeUserModel::where('prid',$param['id'])->where('prid',$param['id'])->update(['update_time' => date('Y-m-d H:i:s',time())]);
                    }else{
                        PrizeUserModel::create(['prid'=>$param['id'],'user_id'=>$value,'create_time' => date('Y-m-d H:i:s',time())]);
                    }
                }
            }else{
                $where=[
                    ['prid','=',$param['id']]
                ];
                PrizeUserModel::where($where)->delete();
            }
            $re_data =  self::where('id',$param['id'])->update($data);
//            if($re_data){
//                return Res::ok('编辑成功');
//            }else{
//                return Res::error('编辑失败');
//            }
            return Res::ok('编辑成功');
        }catch (\Exception $e){
            return json($e->getMessage());
        }
       
    }
    //发起开奖
    public static function sendPrize($param)
    {
        $lott_state = self::where('brid',$param['liveId'])->where('lott_state',0)->where('status',3)->find();
        if ($lott_state == true){
            return Res::error('有奖项未开不能发起抽奖！');
        }
        $resDate =  self::where('id',$param['id'])->field('countdown')->find();
        $room_time = date('Y-m-d H:i:s',time() + $resDate['countdown']);
        $re_data = self::where('id',$param['id'])->update(['status'=>1,'room_time'=>$room_time,'update_time'=>date('Y-m-d H:i:s',time())]);
        $data = self::where('id',$param['id'])->field('id,brid,status,countdown,create_time,title,im_url,room_time,pose_state')->find();
        if($re_data){
            return Res::ok($data);
        }else{
            return Res::error('发起失败');
        }
    }
    public static function getfinish($id)
    {
        $re_data = self::where('id',$id)->where('status',1)->update(['status'=>3,'update_time'=>date('Y-m-d H:i:s',time())]);
        return Res::ok('结束成功');
            
    }
    public static function finishPrize($id)
    {
        $re_data = self::where('id',$id)->update(['status'=>3,'update_time'=>date('Y-m-d H:i:s',time())]);
        $data = self::where('id',$id)->field('id,title,im_url,status')->find();
        if($re_data){
            return Res::ok($data);
        }else{
            return Res::error('结束失败');
        }
    }
    //开奖
    public static function getaddLottery($param)
    {
        
        $id=$param['id'];
        $darw_state=$param['darw_state'];

       
        $prize_info = Db::name('siyu_prize')->where(['id'=>$id])->find();
        if(!$prize_info){
            return Res::error('开奖失败');
        }
        //修改奖项状态
        $update_data=['lott_state'=>1,'darw_state'=>$darw_state,'lott_time'=>date('Y-m-d H:i:s',time())];
        Db::name('siyu_prize')->where(['id'=>$id])->update($update_data);
        switch($prize_info['pose_state']){
            case 0://未预设
                $list = Db::name('siyu_prize_user_lottery')->where(['brid'=>$prize_info['brid'],'prid'=>$prize_info['id']])->select()->toArray(); 
                if(count($list)>$prize_info['number']){
                    $list = array_column($list,null,'id');
                    $ids = array_rand($list,$prize_info['number']);
                }else{
                    $ids = array_keys(array_column($list,null,'id'));
                }
                if($ids){
                    Db::name('siyu_prize_user_lottery')->whereIn('id',$ids)->update(['state'=>1,'update_time'=>date('Y-m-d H:i:s',time())]);
                }
                break;
            case 1://预设
                $user_list = Db::name('siyu_prize_user')->where(['prid'=>$prize_info['id']])->select()->toArray();
                if(count($user_list)>$prize_info['number']){
                    $list = array_column($user_list,null,'id');
                    $ids = array_rand($list,$prize_info['number']);
                }else{
                    $ids = array_keys(array_column($user_list,null,'id'));
                }

                if($ids){
                    Db::name('siyu_prize_user')->whereIn('id',$ids)->update(['status'=>1,'update_time'=>date('Y-m-d H:i:s',time())]);
                }
                
                if($prize_info['number']-count($ids)>0){
                    $number = $prize_info['number']-count($ids);
                    $user_list = Db::name('siyu_prize_shuziren_user')->where(['prid'=>$prize_info['id']])->select()->toArray();
                    if(count($user_list)>$number){
                        $list = array_column($user_list,null,'id');
                        $ids = array_rand($list,$number);
                    }else{
                        $ids = array_keys(array_column($user_list,null,'id'));
                    }
                    if($ids){
                        Db::name('siyu_prize_shuziren_user')->whereIn('id',$ids)->update(['status'=>1,'update_time'=>date('Y-m-d H:i:s',time())]);
                    }
                }
                break;
            default:
                break;
        }
        $data = self::where('id',$param['id'])->find();
        return Res::ok($data);
    }
}